<script setup>
import { ref, watchEffect, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/store";
import { storeToRefs } from "pinia";

const router = useRouter();
const userStore = useUserStore();
const { isLogin, userInfo } = storeToRefs(userStore);

const showMsgDropdown = ref(false);
const messages = ref([]); // 接收的消息列表
const unreadCount = ref(0);

// 状态管理：控制下拉菜单显示/隐藏
const userMenuVisible = ref(false);

// 检查登录状态的函数
const checkAuth = () => {
  const token = localStorage.getItem("token");
  const userId = localStorage.getItem("userId");
  return !!(token && userId);
};

// 页面加载时检查登录状态
onMounted(() => {
  // 确保初始状态正确
  userStore.updateLoginStatus();
const uid = localStorage.getItem("userId");
  if (uid) {
    const socket = new WebSocket(`ws://localhost:8080/app/testWebSocket/${uid}`);


   socket.onmessage = (event) => {
     console.log("收到WebSocket消息:", event.data);
     let msg;
     try {
       msg = JSON.parse(event.data);
     } catch (e) {
       console.error("解析 WebSocket 数据失败：", e, event.data);
       return;
     }

     // 补齐字段并强制类型转换（保证 status 是数字）
     msg.time = msg.time ? Number(msg.time) : Date.now();
     // 如果后端发 "0"/"1"（字符串）也能正确处理
     msg.status = Number(msg.status ?? 0);

    // 将最新消息放到最前面
     messages.value.unshift(msg);
     // 为保证视图强制刷新（在某些边缘情况下有帮助）
     messages.value = [...messages.value];

     // 计算未读：把 status 转为数字后比较
     unreadCount.value = messages.value.filter(m => Number(m.status) === 0).length;
   };


    socket.onopen = () => console.log("✅ WebSocket连接成功");
    socket.onclose = () => console.log("❌ WebSocket连接关闭");
  }
  // 检查是否有重定向路径
  const redirectPath = localStorage.getItem("redirectPath");
  const redirectQuery = localStorage.getItem("redirectQuery");

  if (redirectPath && checkAuth()) {
    localStorage.removeItem("redirectPath");
    localStorage.removeItem("redirectQuery");

    const query = redirectQuery ? JSON.parse(redirectQuery) : {};
    router.push({
      path: redirectPath,
      query: query,
    });
  }
});

// 退出登录方法
const logout = () => {
  // 清除本地存储的用户信息
  localStorage.removeItem("token");
  localStorage.removeItem("userId");
  localStorage.removeItem("userName");
  localStorage.removeItem("redirectPath");
  localStorage.removeItem("redirectQuery");

  // 更新用户状态
  userStore.updateLoginStatus();

  // 更新本地登录状态和菜单显示
  userMenuVisible.value = false;

  // 跳转到首页
  router.push("/reying");

  // 显示退出成功提示
  alert("退出登录成功！");
};

// 处理个人中心菜单项点击
const handleUserMenuClick = (action) => {
  userMenuVisible.value = false;
  const userId = localStorage.getItem('userId');
   console.log("个人中心菜单点击:", action, "userId:", userId); // 调试日志
  
  switch (action) {
    case "myorder":
      router.push("/myorder");
      break;
    case "mycomment":
      router.push("mycomment");
      break;
    case "member":
      router.push("/member");
      break;
    case "mycoupon":
      // 修复：传递 userId 到我的优惠券页面
      router.push({
        path: '/mycouponList',
        query: { userId: userId }
      });
      break;
    case "logout":
      logout();
      break;
    
  }
};
// 标记消息为已读的函数
const markMessageRead = async (messageId) => {
  const messageIndex = messages.value.findIndex(m => m.id === messageId);
  if (messageIndex !== -1) {
    messages.value[messageIndex].status = 1; // 标记为已读
  }
};
const goToCommentPage = async (msg) => {
  console.log('点击的消息对象:', msg); 
  
  // 如果消息已经是已读状态，直接跳转
  if (msg.status === 1) {
    router.push({
      path: '/movieDetail',
      query: {
        movieId: msg.movieId || msg.movieid, // 兼容不同字段名
        movieName: msg.movieName,
        moviePoster: msg.moviePoster,
        score: msg.score,
        boxOffice: msg.boxOffice,
        releaseDate: msg.releaseDate
      }
    });
    return;
  }
  
  try {
    // 先更新本地状态，立即让红点消失
    const messageIndex = messages.value.findIndex(m => m.id === msg.id);
    if (messageIndex !== -1) {
      messages.value[messageIndex].status = 1; // 立即标记为已读
    }
    
    // ✅ 触发响应更新，让红点立即消失
    messages.value = [...messages.value];
    
    // ✅ 立即更新未读数
    unreadCount.value = messages.value.filter(m => Number(m.status) === 0).length;
     console.log('更新后的未读数:', unreadCount.value);
    
    
 // 跳转到电影详情页
    router.push({
      path: '/movieDetail',
      query: {
        movieId: msg.movieId || msg.movieid,
        movieName: msg.movieName,
        moviePoster: msg.moviePoster,
        score: msg.score,
        boxOffice: msg.boxOffice,
        releaseDate: msg.releaseDate
      }
    });
  } catch (error) {
    console.error('处理消息点击失败:', error);
    
  }
};
// 点击页面其他位置时关闭下拉
document.addEventListener("click", () => {
  showMsgDropdown.value = false;
});

</script>

<template>
  <div>
    <div
      class="app-container"
      style="
        min-height: 100vh;
        display: flex;
        flex-direction: column;
        background-color: #f9f9f9;
      "
    >
      <!-- 公共导航栏 - 全屏宽度 -->
      <header
        class="navbar"
        style="
          background-color: #a2131d;
          color: white;
          height: 60px;
          display: flex;
          align-items: center;
          padding: 0 20px;
          width: 100%;
          min-width: 1200px;
        "
      >
        <!-- 网站Logo -->
        <div class="logo" style="display: flex; align-items: center">
          <div
            style="
              width: 40px;
              height: 40px;
              margin-right: 10px;
              background-color: #fff;
              border-radius: 4px;
              display: flex;
              align-items: center;
              justify-content: center;
            "
          >
            <span style="color: #a2131d; font-weight: bold">RW</span>
          </div>
          <span style="font-size: 20px; font-weight: bold">荏闻电影</span>
        </div>

        <!-- 城市定位 -->
        <div class="location" style="margin-left: 20px; font-size: 14px">
          北京
        </div>

        <!-- 导航链接区域 -->
        <nav
          class="nav-links"
          style="
            margin-left: auto;
            display: flex;
            gap: 25px;
            align-items: center;
          "
        >
          <RouterLink
            to="/reying"
            class="nav-item"
            active-class="active"
            style="
              color: white;
              text-decoration: none;
              cursor: pointer;
              font-weight: bold;
            "
          >
            首页
          </RouterLink>
          <RouterLink
            to="/cinemaList"
            class="nav-item"
            active-class="active"
            style="color: white; text-decoration: none; cursor: pointer"
          >
            影院
          </RouterLink>
          <RouterLink
            to="/couponList"
            class="nav-item"
            active-class="active"
            style="color: white; text-decoration: none; cursor: pointer"
          >
            优惠券
          </RouterLink>
          <!-- 消息通知 -->
          <div
            class="notification"
            style="position: relative; cursor: pointer;"
            @click.stop="showMsgDropdown = !showMsgDropdown"
          >

            <!-- 图标 -->
            <span style="font-size: 20px;">🔔</span>

            <!-- 小红点 -->
            <span
              v-if="unreadCount > 0"
              style="
                position: absolute;
                top: -2px;
                right: -5px;
                background: #ff4d4f;
                color: white;
                border-radius: 50%;
                padding: 2px 6px;
                font-size: 12px;
              "
            >
              {{ unreadCount }}
            </span>

            <!-- 消息下拉层 -->
            <div
              v-if="showMsgDropdown"
              style="
                position: absolute;
                top: 50px;
                right: 0;
                width: 260px;
                background: white;
                border-radius: 6px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                padding: 12px 0;
                z-index: 200;
              "
            >
              <div v-if="messages.length === 0" style="padding:12px; text-align:center; color:#999;">
                暂无新消息
              </div>

            <!-- 在消息下拉层的消息项样式 -->
              <div
                v-for="m in messages"
                :key="m.id"
                style="
                  padding: 10px 15px;
                  border-bottom: 1px solid #f5f5f5;
                  cursor: pointer;
                  transition: background-color 0.2s;
                "
                @click="goToCommentPage(m)"
                class="message-item"
                :style="{
                  backgroundColor: m.status === 0 ? '#f8f9fa' : 'white'
                }"
              >
                <div style="font-size:14px; color:#333;">
                  🎬《{{ m.movieName }}》有新回复：
                  <span 
                    style="color:#a2131d; font-weight:bold;"
                    :style="{
                      fontWeight: m.status === 0 ? 'bold' : 'normal'
                    }"
                  >
                    {{ m.content }}
                  </span>
                </div>
                <div style="font-size:12px; color:#999; margin-top:4px;">
                  {{ new Date(m.time).toLocaleString() }}
                </div>
              </div>
            </div>
          </div>

          <!-- 根据登录状态显示不同内容 -->
          <template v-if="isLogin">
            <!-- 已登录：显示个人中心及下拉菜单 -->
            <div
              class="user-center"
              style="
                position: relative;
                height: 60px;
                display: flex;
                align-items: center;
                padding: 0 10px;
              "
              @mouseenter="userMenuVisible = true"
              @mouseleave="userMenuVisible = false"
            >
              <!-- 个人中心触发按钮 -->
              <a
                style="
                  color: white;
                  text-decoration: none;
                  cursor: pointer;
                  display: flex;
                  align-items: center;
                "
              >
                个人中心
                <span style="margin-left: 5px">▼</span>
              </a>

              <!-- 下拉菜单 -->
              <div
                class="user-menu"
                v-if="userMenuVisible"
                style="
                  position: absolute;
                  top: 60px;
                  right: 0;
                  background-color: white;
                  color: #333;
                  border-radius: 4px;
                  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                  min-width: 150px;
                  padding: 10px 0;
                  z-index: 100;
                "
                @mouseenter="userMenuVisible = true"
                @mouseleave="userMenuVisible = false"
              >
                <div
                  style="
                    display: block;
                    padding: 8px 20px;
                    color: #333;
                    text-decoration: none;
                    cursor: pointer;
                  "
                  @click="handleUserMenuClick('myorder')"
                >
                  我的订单
                </div>
                <div
                  style="
                    display: block;
                    padding: 8px 20px;
                    color: #333;
                    text-decoration: none;
                    cursor: pointer;
                  "
                  @click="handleUserMenuClick('member')"
                >
                  会员信息
                </div>
                <div
                  style="
                    display: block;
                    padding: 8px 20px;
                    color: #333;
                    text-decoration: none;
                    cursor: pointer;
                  "
                  @click="handleUserMenuClick('mycoupon')"
                >
                  我的优惠券
                </div>
                  <div
                  style="
                    display: block;
                    padding: 8px 20px;
                    color: #333;
                    text-decoration: none;
                    cursor: pointer;
                  "
                  @click="handleUserMenuClick('mycomment')"
                >
                  我的评价
                </div>
                <div
                  style="height: 1px; background-color: #f0f0f0; margin: 5px 0"
                ></div>
                <div
                  style="
                    display: block;
                    padding: 8px 20px;
                    color: #333;
                    text-decoration: none;
                    cursor: pointer;
                  "
                  @click="handleUserMenuClick('logout')"
                >
                  退出登录
                </div>
              </div>
            </div>
          </template>
          <template v-else>
            <!-- 未登录：显示登录和注册链接 -->
            <RouterLink
              to="/login"
              class="nav-item"
              active-class="active"
              style="color: white; text-decoration: none; cursor: pointer"
            >
              登录
            </RouterLink>
            <RouterLink
              to="/register"
              class="nav-item"
              active-class="active"
              style="color: white; text-decoration: none; cursor: pointer"
            >
              注册
            </RouterLink>
          </template>
        </nav>
      </header>

      <!-- 页面内容区域 -->
      <main style="flex: 1; padding: 20px">
        <RouterView />
      </main>
    </div>
  </div>
</template>

<style>
/* 全局基础样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
  color: #333;
}

/* 图片基础样式 */
img {
  display: inline-block;
  max-width: 100%;
}

/* 按钮交互样式 */
button {
  transition: all 0.2s ease;
}

button:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

/* 卡片通用样式 */
.movie-card,
.order-summary,
.payment-info {
  box-shadow: 0 4px 12px rgba(162, 19, 29, 0.1);
  border: 1px solid rgba(162, 19, 29, 0.1);
}

/* 导航链接交互样式 */
.nav-item {
  transition: color 0.2s ease;
  padding: 5px 10px;
  border-radius: 4px;
}

.nav-item:hover,
.nav-item.active {
  color: rgba(255, 255, 255, 0.9);
  background-color: rgba(255, 255, 255, 0.1);
}

/* 个人中心下拉菜单交互样式 */
.user-menu div {
  transition: all 0.2s ease;
  cursor: pointer;
}

.user-menu div:hover {
  background-color: #f5f5f5;
  color: #a2131d;
}

/* 修复下拉菜单间隙问题 */
.user-center::before {
  content: "";
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  height: 10px; /* 连接区域高度 */
  background: transparent;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .navbar {
    min-width: 100% !important;
    padding: 0 10px !important;
  }

  .nav-links {
    gap: 15px !important;
  }

  .logo span {
    font-size: 16px !important;
  }

  .location {
    display: none;
  }
}
/* 消息项悬停效果 */
.message-item:hover {
  background-color: #f0f0f0 !important;
}

/* 未读消息样式 */
.message-item.unread {
  background-color: #f8f9fa;
  border-left: 3px solid #a2131d;
}

/* 确保下拉菜单内容可点击 */
.notification .message-item {
  user-select: none;
  -webkit-user-select: none;
}
</style>
